package util

import (
	"bytes"
	"errors"
	log "github.com/sirupsen/logrus"
	"io/ioutil"
	"net/http"
	"os"
	"os/exec"
	"path/filepath"
	"runtime"
	"strings"

	"github.com/gin-gonic/gin"
)

// 程序执行环境配置 dev test prod
func GetRunEnv() string {
	return os.Getenv("run_env")
}

// 获取可执行程序当前路径
func BinaryPathGet() (path string, err error) {
	file, err := exec.LookPath(os.Args[0])
	if err != nil {
		return
	}

	path, err = filepath.Abs(file)
	if err != nil {
		return
	}
	if runtime.GOOS == "windows" {
		path = strings.Replace(path, "\\", "/", -1)
	}

	i := strings.LastIndex(path, "/")
	if i < 0 {
		err = errors.New(`没有找到字符“/”或者"\"`)
		return
	}
	path = path[0 : i+1]
	return
}

func PrintReq() gin.HandlerFunc {
	return func(c *gin.Context) {
		// 不打印有文件的请求
		if c.ContentType() == "multipart/form-data" {
			return
		}
		params, _ := ioutil.ReadAll(c.Request.Body)
		if err := c.Request.Body.Close(); err != nil {
			panic(err)
		}
		// 这里有意思，呵呵
		c.Request.Body = ioutil.NopCloser(bytes.NewBuffer(params))
		paramsStr := string(params)
		log.Infof("Get Request#req_url: %s, params: %s ", c.Request.RequestURI, paramsStr)
	}
}

// 处理Http请求
func HttpReq(r *http.Request) (*http.Response, error) {
	httpClient := &http.Client{}
	return httpClient.Do(r)
}

// 发起Get请求
func ProxyReq(targetUrl string) (*http.Response, error) {
	req, _ := http.NewRequest("GET", targetUrl, nil)
	return HttpReq(req)
}
